package com.reny.ll.git.base_logic

import androidx.lifecycle.viewModelScope
import com.reny.ll.git.base_logic.api.exceptionProcess
import com.reny.ll.git.base_logic.ext.isEmpty
import com.reny.ll.git.mvvm.BaseViewModel
import kotlinx.coroutines.*

abstract class MViewModel : BaseViewModel() {


    //---------  协程  -----------------

    private val crashLogger = { throwable: Throwable -> throwable.printStackTrace() }

    private val jobs = mutableListOf<Job>()

    fun launch(
        exceptionHandler: ((Throwable) -> Unit)? = exceptionProcess(),
        hideLoading: Boolean = true,
        task: suspend CoroutineScope.() -> Unit
    ): Job {
        return viewModelScope.launch {
            try {
                task()
                if (hideLoading){
                    hideLoading()
                }
            } catch (e: Throwable) {
                if("Job was cancelled" != e?.message) {
                    exceptionHandler?.let { it(e) }
                }
            }
        }.apply {
            jobs.add(this)
        }
    }

    override fun onCleared() {
        super.onCleared()
        cancelJobs(jobs)
    }

    private fun cancelJobs(jobs: List<Job>){
        try {
            jobs.forEach {
                it.cancelChildren()
                it.cancel()
            }
        }catch (e: Exception){}
    }

    fun launchGlobal(
        exceptionHandler: ((Throwable) -> Unit)? = crashLogger,
        task: suspend CoroutineScope.() -> Unit
    ): Job {
        val job = GlobalScope.launch {
            try {
                task()
            } catch (e: Throwable) {
                exceptionHandler?.let { it(e) }
            }
        }
        return job
    }

}